package task

import db.Cargo
import db.Wares
import ext.log
import manager.AppManager
import manager.AsyncTask
import manager.NetworkManager
import manager.WaresManager
import org.json.JSONObject

/**
 * 重新加载商品属性
 * 修改商品属性时 调用
 */
class RefreshWaresTask : Runnable {

    private fun exec() {
        log("开始从后台重新加载商品属性")
        val result = NetworkManager.refreshWaresWithServer()
        log("--$result", "商品数据")
        if (result == "no_replen_finished") { // 补货为空
            log("没有库存")
            Wares.delete()
            Cargo.delete()
            WaresManager.reloadWithDatabase()
            return
        }
        saveToTable(result)
        WaresManager.reloadWithDatabase()
    }

    private fun saveToTable(result: String) {
        Wares.delete()
        val root = JSONObject(result)
        val machCode = root.getString("MachCode")
        AppManager.MachCode = machCode
        val arr = root.getJSONArray("arr")
        val length = arr.length()
        for (i in 0 until length) {
            val obj = arr.getJSONObject(i)
            val waresId = obj.getString("WaresId")
            val waresName = obj.getString("WaresName")
            val waresPrice = obj.getDouble("WaresPrice")
            val waresImage1 = obj.getString("WaresImage1")
            val waresImage2 = obj.getString("WaresImage2")
            val waresImage3 = obj.getString("WaresImage3")
            val starValue = obj.getInt("StarValue")
            val waresDiscr = obj.getString("WaresDiscr")
            val wave = obj.getDouble("Microwaveheating")
            val infr = obj.getDouble("Infraredheating")
            val tempValue = obj.getDouble("Cooking")
            val heatDissipationTime = obj.optInt("HeatDissipationTime", 15)
            val wares = Wares(
                waresId,
                waresName,
                waresPrice,
                waresImage1,
                waresImage2,
                wave,
                infr,
                tempValue,
                starValue,
                waresDiscr,
                waresImage3,
                heatDissipationTime
            )
            wares.insert()
        }
    }

    override fun run() {
        try {
            exec()
        } catch (e: Exception) {
            e.printStackTrace()
            AsyncTask.postDelayed(this, 5 * 1000)
        }
    }

}
